package xyz.chaobei.springbootstudy.test;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class ProxyFactory implements MethodInterceptor {

    //维护目标对象
    private Object target;

    public ProxyFactory(Object target) {
        this.target = target;
    }

    private void before() {
        System.out.println("代理类前置处理。。");
    }

    private void after() {
        System.out.println("代理类后置处理。。");
    }

    public Object getProxy() {
        //1.工具类
        Enhancer en = new Enhancer();
        //2.设置父类
        en.setSuperclass(target.getClass());
        //3.设置回调函数
        en.setCallback(this);
        //4.创建子类(代理对象)
        return en.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        /**
         * 执行方法
         */
        this.before();
        Object result = method.invoke(target, objects);
        this.after();
        return result;
    }
}
